//
// Created by Aimeow on 2022/12/1.
//

import Foundation
import UIKit

class SecurityTopVC: SubLevelViewController, PullToRefreshPresentable {
    var datas: [BaglSecurityInfoRwjlModel] = []
    let customV = BSCustomDateView()
    
    var param =  SecurityParam()
    
    var pageNum: Int = 1
    var totalPage: Int64 = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "任务详情"
        view.backgroundColor = .bg
        navigationController?.navBarStyle(.white)
        setupUI()
        setupPullToRefresh(on: tableView, bottomRefreshing: false)

        if deptName == nil {
            deptName = BSUser.currentUser.deptName
            deptId = BSUser.currentUser.deptId
        }
        
        param.deptId = deptId
        param.date = date
        param.dateType = dateEnum.rawValue
        param.ownerId = ownerId

        customV.resetUI(date: date, type: dateEnum)

        reloadData()
    }
    
    deinit {
        tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        reloadData()
    }
    
    func reloadData() {
        // 保安统计情况
        API.getBaglSecurityInfo(withParam: param) { responseModel in
            self.datas = responseModel.model?.rwjl ?? []
            DispatchQueue.main.async {
                self.situationPanel.reload(withModal: responseModel.model?.qdwc)
                self.statusView.reload(withModal: responseModel.model?.rwwcqk)
                self.tableView.tableShowEmpty(withDataCount: self.datas.count)
                self.tableView.reloadData()
            }
        }
    }

    // MARK: - Setup

    func setupUI() {
        let basicBV = UIView.createBase()
        view.addSubview(basicBV)
        basicBV.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(10)
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenWidth - 20)
            make.height.equalTo(62)
        }
        
        customV.delegate = self
        basicBV.addSubview(customV)
        customV.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(35)
            make.centerY.equalToSuperview()
        }
        
        view.addSubview(situationPanel)
        situationPanel.snp.makeConstraints { make in
            make.top.equalTo(basicBV.snp.bottom).offset(10)
            make.left.equalTo(basicBV.snp.left)
            make.right.equalTo(basicBV.snp.right)
        }

        view.addSubview(statusView)
        statusView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(situationPanel.snp.bottom)
        }

        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.equalTo(basicBV.snp.left)
            make.right.equalTo(basicBV.snp.right)
            make.top.equalTo(statusView.snp.bottom)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    lazy var situationPanel: CheckSituationPanel = {
        let view = CheckSituationPanel()
        return view
    }()

    lazy var statusView: SecurityTopStatusiew = {
        let view = SecurityTopStatusiew()
        return view
    }()

    lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.layer.cornerRadius = 10
        tableView.layer.masksToBounds = true
        tableView.register(TaskListCell.self, forCellReuseIdentifier: "TaskListCellIdentifier")
        return tableView
    }()
}

extension SecurityTopVC: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas[indexPath.row]
        let cell = (tableView.dequeueReusableCell(withIdentifier: "TaskListCellIdentifier", for: indexPath)) as! TaskListCell
        cell.selectionStyle = .none
        cell.buildData(data: data)
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = datas[indexPath.row]
        navigationController?.pushViewController(SecurityTaskDetailVC(withId: data.id), animated: true)
    }

    public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        tableView.setCornerRadiusSection(willDisplay: cell, forRowAt: indexPath)
    }
}

extension SecurityTopVC: BSCustomDateViewDelegate {
    func didSelected(year: Int, quarter: Int?, month: Int?, day: Int?, dateEnum: CustomDateEnum) {
        let m = month ?? 1
        let d = day ?? 1
        self.date = "\(year)-\(m < 10 ? "0\(m)" : "\(m)")-\(d < 10 ? "0\(d)" : "\(d)")"
        self.dateEnum = dateEnum

        param.dateType = dateEnum.rawValue
        param.date = self.date
        
        self.reloadData()
    }
}

class SecurityTopStatusiew: UIView {
    let rateV = TaskFinishRateView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
    let summaryItem = TaskHomeItemView()
    let finishItem = TaskHomeItemView()
    let unfinishItem = TaskHomeItemView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    func reload(withModal modal: SecurityBmQdWcQkModel?) {
        rateV.valL.text = "\(modal?.rwwcl ?? "0")%"
        summaryItem.val = modal?.rws ?? "0"
        finishItem.val = modal?.ywcs ?? "0"
        unfinishItem.val = modal?.wwcs ?? "0"
    }
    
    func reload(withModal modal: BaglSecurityInfoRwwcqkModel?) {
        rateV.valL.text = "\(modal?.zwcl ?? 0)%"
        summaryItem.val = "\(modal?.rwzs ?? 0)"
        finishItem.val = "\(modal?.wcs ?? 0)"
        unfinishItem.val = "\(modal?.wwcs ?? 0)"
    }
    
    func setupUI() {
        let baseV = UIView.createBase()
        addSubview(baseV)
        baseV.snp.makeConstraints { make in
            make.top.equalTo(self.snp.top).offset(10)
            make.left.equalTo(self.snp.left).offset(10)
            make.right.equalTo(self.snp.right).offset(-10)
            make.bottom.equalTo(self.snp.bottom).offset(-10)
            make.width.equalTo(ScreenWidth - 20)
        }
        
        let baseTV = TitleItemView()
        baseTV.title = "任务完成情况"
        baseV.addSubview(baseTV)
        baseTV.snp.makeConstraints { make in
            make.top.equalTo(baseV.snp.top)
            make.left.right.equalToSuperview()
            make.height.equalTo(46)
        }
        
        rateV.valL.text = "0%"
        baseV.addSubview(rateV)
        rateV.snp.makeConstraints { make in
            make.top.equalTo(baseTV.snp.bottom).offset(10)
            make.left.equalTo(baseV.snp.left).offset(10)
            make.width.height.equalTo(90)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        let itemWidth = (ScreenWidth - 130.0) / 3.0
        summaryItem.key = "任务总数"
        summaryItem.val = "0"
        baseV.addSubview(summaryItem)
        summaryItem.snp.makeConstraints { make in
            make.top.equalTo(rateV.snp.top)
            make.left.equalTo(rateV.snp.right).offset(4)
            make.width.equalTo(itemWidth)
        }
        
        let vLine1 = UIView()
        vLine1.backgroundColor = .hex("#F5F5F5")
        addSubview(vLine1)
        vLine1.snp.makeConstraints { make in
            make.left.equalTo(summaryItem.snp.right)
            make.centerY.equalTo(rateV.snp.centerY)
            make.height.equalTo(42)
            make.width.equalTo(0.5)
        }
        
        finishItem.key = "已完成"
        finishItem.val = "0"
        baseV.addSubview(finishItem)
        finishItem.snp.makeConstraints { make in
            make.top.equalTo(rateV.snp.top)
            make.left.equalTo(summaryItem.snp.right)
            make.width.equalTo(itemWidth)
        }
        
        let vLine2 = UIView()
        vLine2.backgroundColor = .hex("#F5F5F5")
        addSubview(vLine2)
        vLine2.snp.makeConstraints { make in
            make.left.equalTo(finishItem.snp.right)
            make.centerY.equalTo(rateV.snp.centerY)
            make.height.equalTo(42)
            make.width.equalTo(0.5)
        }
        
        unfinishItem.key = "未完成"
        unfinishItem.val = "0"
        unfinishItem.valL.textColor = .hex("#F17854")
        baseV.addSubview(unfinishItem)
        unfinishItem.snp.makeConstraints { make in
            make.top.equalTo(rateV.snp.top)
            make.left.equalTo(finishItem.snp.right)
            make.width.equalTo(itemWidth)
        }
    }
}

